import datetime

import requests
import xlwt
from xlutils.copy import copy
from xlwt import *

import readConfig as readConfig
import os
import xlrd
from xml.etree import ElementTree as ElementTree
from common import configHttp as configHttp
from common.Log import Logg

log=Logg()#调用初始化
import json
# 导入方法读取baseurl-实例化
localReadConfig = readConfig.ReadConfig()
# 获取文件的路径
proDir = readConfig.proDir
# 这里调用了
localConfigHttp = configHttp.ConfigHttp()
caseNo = 0

#获取学生端登陆token 公共方法
def get_visitor_token():
    send_param = {"phone": 14050000000, "password": "e10adc3949ba59abbe56e057f20f883e", "messageCode": "0",
        "loginType": "1", "timestamp": "0"}
    urllist = localReadConfig.get_http("BASEURL")
    headers = {"Content-Type": 'application/json'}
    res = requests.post("http://"+urllist + "/backend/student/unauth/login",json=send_param, headers=headers)
    #打印json返回值
    info = res.json()
    #header中获取token
    token=res.headers['authorization']
    logger=log.get_logger()
    logger.debug("Create token:%s" % (token))
    return token

#返回接口信息信息公共方法
def show_return_msg(response):
    # 返回response返回信息
    url = response.url
    # 返回json返回值
    msg = response.text
    print("\n请求地址：" + url)
    # 可以显示中文
    print("\n请求返回值：" + '\n' + json.dumps(json.loads(msg), ensure_ascii=False, sort_keys=True, indent=4))


# 从excel文件中读取测试用例
def get_xls(xls_name, sheet_name):
    """
    get interface data from xls file
    :return:
    """
    cls = []
    # 获取xls文件的路径
    xlsPath = os.path.join(proDir, "testFile", 'case', xls_name)
    #D:\interfaceTest\testFile\case\userCase.xlsx
    # 打开文件
    file = xlrd.open_workbook(xlsPath)
    # 按照名称获取工作列表
    sheet = file.sheet_by_name(sheet_name)
    # 获取页的一行
    nrows = sheet.nrows
    for i in range(nrows):
        if sheet.row_values(i)[0] != u'case_name':
            cls.append(sheet.row_values(i))
    return cls


def readPremiumTable(filename):
    """
    读取费率测试数据表格
    :param filename: 数据表名
    :return:
    """
    filePath = os.path.join(proDir, "testFile", 'case', filename)
    file = xlrd.open_workbook(filePath)
    sheet = file.sheet_by_index(0)
    result = []
    for i in range(1, sheet.nrows):
        r_values = sheet.row_values(i)
        result.append(r_values)
    # print(result)
    return result


def writePremiumReuslt(filename, excepctList, actualList, **kwargs):
    now = datetime.datetime.now().strftime('%Y-%m-%d_%H-%M-%S')
    # print(now)
    filepath = os.path.join(proDir, "result", filename)
    # 如果没有该文件则创建
    if not os.path.exists(filepath):
        f = open(filepath, "w")
        f.close()
        workbook = xlwt.Workbook(encoding="utf-8")
        sheet = workbook.add_sheet("sheet1")
        sheet.write(0, 0, "产品代码")
        sheet.write(0, 1, "保额")
        sheet.write(0, 2, "性别")
        sheet.write(0, 3, "年龄")
        sheet.write(0, 4, "有无社保")
        sheet.write(0, 5, "缴费年限")
        sheet.write(0, 6, "缴费方式")
        sheet.write(0, 7, "职业代码")
        sheet.write(0, 8, "预期保费")
        sheet.write(0, 9, "实际保费")
        sheet.write(0, 10, "是否匹配")
        workbook.save(filepath)
    rb = xlrd.open_workbook(filepath, formatting_info=True)
    # 获取表格行数，以便在其后追加数据行
    rows = rb.sheet_by_index(0).nrows
    # 复制结果表，以进行数据插入
    wb = copy(rb)
    sheet = wb.get_sheet(0)
    for i in range(0, excepctList[0].__len__()):
        j = i + rows
        sheet.write(j, 0, kwargs.get("salesProductCode"))
        sheet.write(j, 1, kwargs.get("coverage"))
        sheet.write(j, 2, kwargs.get("sex"))
        sheet.write(j, 3, excepctList[1][i])
        sheet.write(j, 4, kwargs.get("hasSecurity"))
        sheet.write(j, 5, kwargs.get("paymentPeriod"))
        sheet.write(j, 6, kwargs.get("paymentMethod"))
        sheet.write(j, 7, kwargs.get("occupationCode"))
        sheet.write(j, 8, '%.2f' % excepctList[0][i])
        sheet.write(j, 9, actualList[i])
        if float(excepctList[0][i]) != float(actualList[i]):
            sheet.write(j, 10, "不匹配", excelBackColor("red"))
        else:
            sheet.write(j, 10, "匹配", excelBackColor("green"))
    wb.save(filepath)
    print("将数据写入表格")

def excelBackColor(name):
    style = XFStyle()
    pattern = Pattern()
    pattern.pattern = Pattern.SOLID_PATTERN
    if name == "red":
        pattern.pattern_fore_colour = 2  # 设置单元格背景色
    else:
        pattern.pattern_fore_colour = 3
    style.pattern = pattern
    return style



if __name__ == "__main__":
    get_visitor_token();
